<template>
  <McLayout class="container">
    <McHeader :title="'医疗智能助手'" :logoImg="''">
      <template #operationArea>
        <div class="operations">
          <i class="icon-helping"></i>
        </div>
      </template>
    </McHeader>
    <McLayoutContent
      v-if="startPage"
      style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px"
    >
      <McIntroduction
        :logoImg="''"
        :title="'医疗智能助手'"
        :subTitle="'您好，欢迎使用医疗智能助手'"
        :description="description"
      ></McIntroduction>
      <McPrompt
        :list="introPrompt.list"
        :direction="introPrompt.direction"
        class="intro-prompt"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
    </McLayoutContent>
    <McLayoutContent class="content-container" v-else>
      <!-- 推荐内容区域 -->
      <div v-if="showRecommendations && recommendations.length > 0" class="recommendations">
        <h4>为您推荐</h4>
        <div class="recommendation-list">
          <div 
            v-for="(rec, index) in recommendations" 
            :key="index" 
            class="recommendation-item"
            @click="onRecommendationClick(rec)"
          >
            {{ rec }}
          </div>
        </div>
      </div>
      
      <!-- 对话消息区域 -->
      <template v-for="(msg, idx) in messages" :key="idx">
        <McBubble
          v-if="msg.from === 'user'"
          :content="msg.content"
          :align="'right'"
          :avatarConfig="{ imgSrc: 'https://via.placeholder.com/40x40?text=User' }"
        >
        </McBubble>
        <McBubble v-else :content="msg.content" :avatarConfig="{ imgSrc: 'https://via.placeholder.com/40x40?text=Doctor' }" :loading="msg.loading"> </McBubble>
      </template>
    </McLayoutContent>
    <div class="shortcut" style="display: flex; align-items: center; gap: 8px">
      <McPrompt
        v-if="!startPage"
        :list="simplePrompt"
        :direction="'horizontal'"
        style="flex: 1"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
      <Button
        icon="history"
        shape="circle"
        title="对话历史"
        size="md"
        @click="loadConversationHistory"
      />
      <Button
        style="margin-left: auto"
        icon="add"
        shape="circle"
        title="新建对话"
        size="md"
        @click="newConversation"
      />
    </div>
    
    <!-- 对话历史侧边栏 -->
    <div v-if="showHistory" class="history-sidebar">
      <div class="history-header">
        <h3>对话历史</h3>
        <Button icon="close" shape="text" @click="showHistory = false" />
      </div>
      <div class="history-list">
        <div 
          v-for="conversation in conversationHistory" 
          :key="conversation.id"
          class="history-item"
          @click="switchToConversation(conversation.id)"
        >
          <div class="history-summary">{{ conversation.summary || '未命名对话' }}</div>
          <div class="history-date">{{ new Date(conversation.messages[0]?.timestamp).toLocaleString() }}</div>
          <div class="history-tags" v-if="conversation.tags">
            <span v-for="tag in conversation.tags" :key="tag" class="history-tag">{{ tag }}</span>
          </div>
        </div>
      </div>
    </div>
    <McLayoutSender>
      <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span v-for="(item, index) in inputFootIcons" :key="index">
                <i :class="item.icon"></i>
                {{ item.text }}
              </span>
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
            </div>
            <div class="input-foot-right">
              <Button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''"><span class="demo-button-content">清空输入</span></Button>
            </div>
          </div>
        </template>
      </McInput>
    </McLayoutSender>
  </McLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { Button } from 'vue-devui/button';
import 'vue-devui/button/style.css';
import OpenAI from 'openai';
import { userBehaviorService } from './services/UserBehaviorService';

const description = [
  '医疗智能助手可以为您提供健康咨询、疾病预防、用药指导、医疗机构查询等医疗健康服务。',
  '作为智能助手，我们将竭诚为您提供专业、高效的服务，但请注意保护好您的健康信息和个人隐私。重要医疗决策请咨询专业医生。',
];
const introPrompt = {
  direction: 'horizontal',
  list: [
    {
      value: 'symptomCheck',
      label: '常见症状咨询',
      iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
      desc: '了解常见症状及可能的原因',
    },
    {
      value: 'medicationGuide',
      label: '用药指导',
      iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
      desc: '药物使用方法和注意事项',
    },
    {
      value: 'diseasePrevention',
      label: '疾病预防',
      iconConfig: { name: 'icon-priority', color: '#3ac295' },
      desc: '各类疾病的预防措施和健康建议',
    },
  ],
};
const simplePrompt = [
  {
    value: 'symptomCheck',
    iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
    label: '常见症状咨询',
  },
  {
    value: 'medicationGuide',
    iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
    label: '用药指导',
  },
  {
    value: 'diseasePrevention',
    iconConfig: { name: 'icon-priority', color: '#3ac295' },
    label: '疾病预防',
  },
  {
    value: 'healthLifestyle',
    iconConfig: { name: 'icon-heart-o', color: '#e74c3c' },
    label: '健康生活方式',
  },
];
const startPage = ref(true);
const inputValue = ref('');
const inputFootIcons = [
  { icon: 'icon-at', text: '智能体' },
  { icon: 'icon-standard', text: '词库' },
  { icon: 'icon-add', text: '附件' },
];

const messages = ref<any[]>([]);
const conversationHistory = ref<any[]>([]);
const showHistory = ref(false);
const recommendations = ref<string[]>([]);
const showRecommendations = ref(true);

// 计算属性：根据用户偏好调整UI
const userPreferences = computed(() => userBehaviorService.getUserPreferences());

// DeepSeek API配置
const client = ref<OpenAI>();

client.value = new OpenAI({
  apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY || '', // 从环境变量读取API Key
  baseURL: import.meta.env.VITE_DEEPSEEK_BASE_URL || 'https://api.deepseek.com', // 从环境变量读取Base URL
  dangerouslyAllowBrowser: true, // 浏览器环境使用需要开启
});

// 组件挂载时初始化
onMounted(() => {
  userBehaviorService.startNewConversation();
  recommendations.value = userBehaviorService.getRecommendations();
});

// 新建对话
const newConversation = () => {
  startPage.value = true;
  messages.value = [];
  userBehaviorService.startNewConversation();
  recommendations.value = userBehaviorService.getRecommendations();
  showRecommendations.value = true;
}

const onSubmit = (evt) => {
  inputValue.value = '';
  startPage.value = false;
  showRecommendations.value = false;
  // 用户发送消息
  messages.value.push({
    from: 'user',
    content: evt,
    avatarConfig: { name: 'user' },
  });

  // 记录用户行为
  userBehaviorService.recordBehavior({
    type: 'query',
    content: evt,
    timestamp: Date.now()
  });

  // 添加到对话历史
  userBehaviorService.addMessageToConversation('user', evt);

  fetchData(evt);
};

// 加载历史对话
const loadConversationHistory = () => {
  conversationHistory.value = userBehaviorService.getConversationHistory();
  showHistory.value = !showHistory.value;
};

// 切换到历史对话
const switchToConversation = (conversationId: string) => {
  userBehaviorService.setCurrentConversation(conversationId);
  // 在实际应用中，这里应该加载该对话的消息
  startPage.value = false;
  showHistory.value = false;
  showRecommendations.value = false;
};

// 点击推荐内容
const onRecommendationClick = (content: string) => {
  onSubmit(content);
};

const fetchData = async (ques) => {
  messages.value.push({
    from: 'model',
    content: '',
    avatarConfig: { name: 'model' },
    id: '',
    loading: true,
  });
  try {
    // 使用fetch API直接调用DeepSeek API，避免OpenAI SDK版本兼容性问题
    const response = await fetch(import.meta.env.VITE_DEEPSEEK_BASE_URL + '/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: 'deepseek-reasoner',
        messages: [
          {
            role: 'system',
            content: '你是一名专业的医疗智能助手，负责为用户提供健康咨询、疾病预防、用药指导、医疗机构查询等医疗健康服务。请使用礼貌、专业的语言回答用户问题，注意保护用户隐私，不泄露敏感信息。如果遇到不确定的问题，请明确告知用户并建议其咨询专业医生。始终强调你只是提供参考信息，不能替代专业医疗诊断和治疗。'
          },
          { role: 'user', content: ques }
        ],
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    messages.value[messages.value.length - 1].loading = false;

    // 处理流式响应
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('No response body');
    }

    const decoder = new TextDecoder('utf-8');
    let accumulatedContent = '';
    let chatId = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n').filter(line => line.trim() !== '');

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.substring(6);
          if (data === '[DONE]') {
            break;
          }
          try {
            const json = JSON.parse(data);
            if (json.id) {
              chatId = json.id;
              messages.value[messages.value.length - 1].id = chatId;
            }
            if (json.choices && json.choices.length > 0) {
              const delta = json.choices[0].delta;
              if (delta && delta.content) {
                accumulatedContent += delta.content;
                messages.value[messages.value.length - 1].content = accumulatedContent;
              }
            }
          } catch (e) {
            console.error('解析流式数据错误:', e);
          }
        }
      }
    }

    // 记录AI回复到对话历史
    userBehaviorService.addMessageToConversation('model', accumulatedContent);
  } catch (error) {
    console.error('DeepSeek API调用错误:', error);
    messages.value[messages.value.length - 1].content = '抱歉，模型调用失败，请稍后重试。';
    messages.value[messages.value.length - 1].loading = false;
  }
};
</script>

<style>
.container {
  width: 1000px;
  margin: 20px auto;
  height: calc(100vh - 82px);
  padding: 20px;
  gap: 8px;
  background: var(--card-background);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow: auto;
}

/* 推荐内容样式 */
.recommendations {
  background: var(--card-background);
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-left: 3px solid var(--primary-color);
}

.recommendations h4 {
  margin: 0 0 12px 0;
  color: var(--text-primary);
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.recommendations h4::before {
  content: '💡';
  font-size: 18px;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.recommendation-item {
  padding: 12px 16px;
  background: rgba(0, 122, 90, 0.05);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--primary-color);
  border: 1px solid transparent;
  position: relative;
  padding-left: 28px;
}

.recommendation-item::before {
  content: '→';
  position: absolute;
  left: 12px;
  transition: transform 0.2s;
}

.recommendation-item:hover {
  background: rgba(0, 122, 90, 0.1);
  border-color: var(--primary-color);
  transform: translateX(4px);
}

.recommendation-item:hover::before {
  transform: translateX(4px);
}

/* 对话历史侧边栏 */
.history-sidebar {
  position: fixed;
  right: 0;
  top: 0;
  width: 360px;
  height: 100vh;
  background: var(--card-background);
  box-shadow: -4px 0 16px rgba(0, 0, 0, 0.08);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
  background: linear-gradient(90deg, var(--primary-color), var(--primary-light));
  color: white;
}

.history-header h3 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.history-header button {
  background: transparent;
  border: none;
  color: white;
  font-size: 18px;
  padding: 4px;
}

.history-header button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  padding: 14px;
  margin-bottom: 10px;
  background: var(--card-background);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid var(--border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
}

.history-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: var(--primary-color);
  border-radius: 3px 0 0 3px;
}

.history-item:hover {
  border-color: var(--primary-color);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.history-summary {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 6px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.history-date {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 6px;
}

.history-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.history-tag {
  font-size: 11px;
  padding: 2px 8px;
  background: rgba(0, 122, 90, 0.1);
  color: var(--primary-color);
  border-radius: 12px;
  border: 1px solid rgba(0, 122, 90, 0.2);
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;

  .input-foot-left {
    display: flex;
    align-items: center;
    gap: 12px;

    span {
      font-size: 14px;
      line-height: 18px;
      color: var(--text-primary);
      cursor: pointer;
      transition: color 0.2s;
    }

    span:hover {
      color: var(--primary-color);
    }

    .input-foot-dividing-line {
      width: 1px;
      height: 14px;
      background-color: var(--border-color);
    }

    .input-foot-maxlength {
      font-size: 14px;
      color: var(--text-secondary);
    }
  }

  .input-foot-right {
    .demo-button-content {
      font-size: 14px;
    }

    & > *:not(:first-child) {
      margin-left: 8px;
    }
  }
}
</style>